use argon2::{Argon2, PasswordHash, PasswordVerifier};
use sea_orm::{QueryFilter, QueryOrder, QuerySelect, Set, TransactionTrait};
use sea_orm::ColumnTrait;
use sea_orm::{DatabaseConnection, EntityTrait};
use async_graphql::Result as GraphQLResult;
use sea_orm::prelude::Decimal;
use snowid::SnowID;
use crate::entity::{merchant_account, merchant_account_bill, order_main, order_product_r, product_main, user_wallet, user_wallet_bill};
use crate::graphql::order_graphql::{CreateOrderInput, OrderConnection, OrderObject, OrderProductObject};


pub async fn get_orders(
    db: &DatabaseConnection,
    user_id: u64,
    limit: u64,
    cursor: Option<u64>,
    status: Option<String>
) -> GraphQLResult<OrderConnection> {

    let mut query = order_main::Entity::find()
        .filter(order_main::Column::UserId.eq(user_id))
        .order_by_desc(order_main::Column::Id)
        .limit(limit + 1);

    // 如果提供了 status 参数，则添加状态筛选条件
    if let Some(status_value) = status {
        if !status_value.is_empty() {
            query = query.filter(order_main::Column::Status.eq(status_value));
        }
    }

    if let Some(cursor_id) = cursor {
        query = query.filter(order_main::Column::Id.gt(cursor_id));
    }

    let orders = query
        .all(db)
        .await
        .map_err(|e| async_graphql::Error::new(format!("查询订单失败: {}", e)))?;

    let has_next = orders.len() as u64 > limit;
    let orders_to_process = if has_next {
        &orders[..limit as usize]
    } else {
        &orders[..]
    };

    let next_cursor = if has_next {
        orders_to_process.last().map(|order| order.id)
    } else {
        None
    };

    let mut order_objects = Vec::new();

    for order in orders_to_process {
        let order_products = order_product_r::Entity::find()
            .filter(order_product_r::Column::OrderId.eq(order.id))
            .all(db)
            .await
            .map_err(|e| async_graphql::Error::new(format!("查询订单商品失败: {}", e)))?
            .into_iter()
            .map(|product| OrderProductObject {
                id: product.id.to_string(),
                order_id: product.order_id.to_string(),
                product_id: product.product_id.to_string(),
                title: product.title,
                cover_addr: product.cover_addr,
                quantity: product.quantity,
                create_time: product.create_time.format("%Y-%m-%d %H:%M:%S").to_string(),
                update_time: product.update_time.format("%Y-%m-%d %H:%M:%S").to_string(),
            })
            .collect();

        let order_object = OrderObject {
            id: order.id.to_string(),
            create_time: order.create_time.format("%Y-%m-%d %H:%M:%S").to_string(),
            update_time: order.update_time.format("%Y-%m-%d %H:%M:%S").to_string(),
            user_id: order.user_id.to_string(),
            status: order.status.clone(),
            total_price: order.total_price.to_string(),
            pay_type: order.pay_type.clone(),
            real_price: order.real_price.to_string(),
            receiver_address: order.receiver_address.clone(),
            receiver_name: order.receiver_name.clone(),
            receiver_phone: order.receiver_phone.clone(),
            pay_time: order.pay_time.as_ref().map(|dt| dt.format("%Y-%m-%d %H:%M:%S").to_string()),
            products: order_products,
        };

        order_objects.push(order_object);
    }

    Ok(OrderConnection {
        orders: order_objects,
        has_next,
        next_cursor,
    })
}

// 根据订单ID查询单个订单
pub async fn get_order_by_id(
    db: &DatabaseConnection,
    order_id: u64,
    user_id: Option<u64>, // 可选的用户ID，用于权限验证
) -> GraphQLResult<OrderObject> {
    // 查询订单
    let order = order_main::Entity::find_by_id(order_id)
        .one(db)
        .await
        .map_err(|e| async_graphql::Error::new(format!("查询订单失败: {}", e)))?
        .ok_or_else(|| async_graphql::Error::new("订单不存在"))?;

    // 如果提供了用户ID，验证订单是否属于该用户
    // if let Some(uid) = user_id {
    //     if order.user_id != uid {
    //         return Err(async_graphql::Error::new("无权访问该订单"));
    //     }
    // }

    // 查询订单关联的商品信息
    let order_products = order_product_r::Entity::find()
        .filter(order_product_r::Column::OrderId.eq(order.id))
        .all(db)
        .await
        .map_err(|e| async_graphql::Error::new(format!("查询订单商品失败: {}", e)))?
        .into_iter()
        .map(|product| OrderProductObject {
            id: product.id.to_string(),
            order_id: product.order_id.to_string(),
            product_id: product.product_id.to_string(),
            title: product.title,
            cover_addr: product.cover_addr,
            quantity: product.quantity,
            create_time: product.create_time.format("%Y-%m-%d %H:%M:%S").to_string(),
            update_time: product.update_time.format("%Y-%m-%d %H:%M:%S").to_string(),
        })
        .collect();

    let order_object = OrderObject {
        id: order.id.to_string(),
        user_id: order.user_id.to_string(),
        total_price: order.total_price.to_string(),
        real_price: order.real_price.to_string(),
        receiver_address: order.receiver_address,
        receiver_name: order.receiver_name,
        receiver_phone: order.receiver_phone,
        pay_type: order.pay_type.clone(),
        pay_time: order.pay_time.as_ref().map(|dt| dt.format("%Y-%m-%d %H:%M:%S").to_string()),
        status: order.status,
        create_time: order.create_time.format("%Y-%m-%d %H:%M:%S").to_string(),
        update_time: order.update_time.format("%Y-%m-%d %H:%M:%S").to_string(),
        products: order_products,
    };

    Ok(order_object)
}

// 创建订单
pub async fn create_order(
    db: &DatabaseConnection,
    user_id: u64,
    input: CreateOrderInput,
) -> GraphQLResult<OrderObject> {
    // 开启事务
    let txn = db.begin().await
        .map_err(|e| async_graphql::Error::new(format!("开启事务失败: {}", e)))?;

    // 计算总价格和实付价格
    let mut total_price = Decimal::ZERO;
    let mut product_details = Vec::new();

    // 查询所有商品的价格信息
    for product_input in &input.products {
        
        let product_id: u64 = product_input.product_id.parse()
            .map_err(|e| async_graphql::Error::new(format!("无效的商品ID: {}", e)))?;
        // 获取商品
        let product = product_main::Entity::find_by_id(product_id)
            .one(&txn)
            .await
            .map_err(|e| async_graphql::Error::new(format!("查询商品信息失败: {}", e)))?
            .ok_or_else(|| async_graphql::Error::new(format!("商品不存在: {}", product_input.product_id)))?;

        // 冻结库存
        // 检查库存是否充足
        if product.stockpile < product_input.quantity {
            return Err(async_graphql::Error::new(format!("商品 {} 库存不足", product.title)));
        }

        // 冻结库存 (增加冻结数量)
        let frozen_stock = product.stockpile_frozen + product_input.quantity;
        let available_stock: u32 = product.stockpile - product_input.quantity;

        // 更新商品冻结库存
        let mut product_active_model: product_main::ActiveModel = product.clone().into();
        product_active_model.stockpile_frozen = Set(frozen_stock);
        product_active_model.stockpile = Set(available_stock);
        product_active_model.update_time = Set(chrono::Utc::now().naive_utc());

        product_main::Entity::update(product_active_model)
            .exec(&txn)
            .await
            .map_err(|e| async_graphql::Error::new(format!("冻结库存失败: {}", e)))?;


        let product_total = product.price * Decimal::from(product_input.quantity);
        total_price += product_total;

        product_details.push((product, product_input.quantity));

    }

    let snow_id = SnowID::new(1)?;
    
    // 创建订单主信息
    let now = chrono::Utc::now().naive_utc();
    let order_model = order_main::ActiveModel {
        id: Set(snow_id.generate()),
        create_time: Set(now),
        update_time: Set(now),
        user_id: Set(user_id),
        total_price: Set(total_price),
        real_price: Set(total_price),
        receiver_address: Set(input.receiver_address),
        receiver_name: Set(input.receiver_name),
        receiver_phone: Set(input.receiver_phone),
        status: Set("non_pay".to_string()), // 初始状态为待支付
        pay_type: Set(None),
        pay_time: Set(None),
    };

    let inserted_order = order_main::Entity::insert(order_model)
        .exec_with_returning(&txn)
        .await
        .map_err(|e| async_graphql::Error::new(format!("创建订单失败: {}", e)))?;

    // 创建订单商品关联信息
    let mut order_products = Vec::new();

    for product_input in product_details {
        let product_model = order_product_r::ActiveModel {
            id: Set(snow_id.generate()),
            create_time: Set(now),
            update_time: Set(now),
            order_id: Set(inserted_order.id),
            product_id: Set(product_input.0.id),
            quantity: Set(product_input.1),
            title: Set(product_input.0.title),
            cover_addr: Set(product_input.0.cover_addr),
        };

        let inserted_product = order_product_r::Entity::insert(product_model)
            .exec_with_returning(&txn)
            .await
            .map_err(|e| async_graphql::Error::new(format!("创建订单商品失败: {}", e)))?;

        order_products.push(OrderProductObject {
            id: inserted_product.id.to_string(),
            create_time: inserted_product.create_time.format("%Y-%m-%d %H:%M:%S").to_string(),
            update_time: inserted_product.update_time.format("%Y-%m-%d %H:%M:%S").to_string(),
            order_id: inserted_product.order_id.to_string(),
            product_id: inserted_product.product_id.to_string(),
            quantity: inserted_product.quantity,
            title: inserted_product.title,
            cover_addr: inserted_product.cover_addr,
        });
    }

    // 提交事务
    txn.commit().await
        .map_err(|e| async_graphql::Error::new(format!("提交事务失败: {}", e)))?;

    // 构建返回对象
    let order_object = OrderObject {
        id: inserted_order.id.to_string(),
        create_time: inserted_order.create_time.format("%Y-%m-%d %H:%M:%S").to_string(),
        update_time: inserted_order.update_time.format("%Y-%m-%d %H:%M:%S").to_string(),
        user_id: inserted_order.user_id.to_string(),
        total_price: inserted_order.total_price.to_string(),
        real_price: inserted_order.real_price.to_string(),
        receiver_address: inserted_order.receiver_address,
        receiver_name: inserted_order.receiver_name,
        receiver_phone: inserted_order.receiver_phone,
        pay_type: inserted_order.pay_type.clone(),
        pay_time: inserted_order.pay_time.as_ref().map(|dt| dt.format("%Y-%m-%d %H:%M:%S").to_string()),
        status: inserted_order.status,
        products: order_products,
    };

    Ok(order_object)
}



// 支付订单
pub async fn pay_order(
    db: &DatabaseConnection,
    order_id: String,
    user_id: u64,
    pay_password: String,
) -> GraphQLResult<OrderObject> {
    // 开启事务
    let txn = db.begin().await
        .map_err(|e| async_graphql::Error::new(format!("开启事务失败: {}", e)))?;

    let order_id: u64 = order_id.parse()
        .map_err(|e| async_graphql::Error::new(format!("无效的订单ID: {}", e)))?;
    // 1. 查询订单信息
    let order = order_main::Entity::find_by_id(order_id)
        .one(&txn)
        .await
        .map_err(|e| async_graphql::Error::new(format!("查询订单失败: {}", e)))?
        .ok_or_else(|| async_graphql::Error::new("订单不存在"))?;

    // 2. 验证订单是否属于当前用户
    // if order.user_id != user_id {
    //     return Err(async_graphql::Error::new("无权操作该订单"));
    // }

    // 3. 验证订单状态是否为待支付
    if order.status != "non_pay" {
        return Err(async_graphql::Error::new("订单状态不正确，无法支付"));
    }

    // 4. 查询用户钱包信息
    let user_wallet_model = user_wallet::Entity::find()
        .filter(user_wallet::Column::UserId.eq(user_id))
        .one(&txn)
        .await
        .map_err(|e| async_graphql::Error::new(format!("查询用户钱包失败: {}", e)))?
        .ok_or_else(|| async_graphql::Error::new("用户钱包不存在"))?;

    let parsed_hash = PasswordHash::new(&user_wallet_model.pay_password)
        .map_err(|_| async_graphql::Error::new("支付密码格式错误"))?;

    let argon2 = Argon2::default();
    argon2
        .verify_password(pay_password.as_bytes(), &parsed_hash)
        .map_err(|_| async_graphql::Error::new("支付密码错误"))?;

    // 5. 检查用户余额是否充足
    if user_wallet_model.balance < order.real_price {
        return Err(async_graphql::Error::new("余额不足，无法支付"));
    }

    // 6. 查询商家账户信息（根据结算账户号）
    let merchant_account_model = merchant_account::Entity::find()
        .filter(merchant_account::Column::SettlementAccount.eq("6222600810123456789"))
        .one(&txn)
        .await
        .map_err(|e| async_graphql::Error::new(format!("查询商家账户失败: {}", e)))?
        .ok_or_else(|| async_graphql::Error::new("商家账户不存在"))?;

    // 7. 更新用户钱包：冻结金额并减少余额
    let updated_user_balance = user_wallet_model.balance - order.real_price;
    let updated_user_frozen_balance = user_wallet_model.frozen_balance + order.real_price;

    let mut user_wallet_active_model: user_wallet::ActiveModel = user_wallet_model.clone().into();
    user_wallet_active_model.balance = Set(updated_user_balance);
    user_wallet_active_model.frozen_balance = Set(updated_user_frozen_balance);
    user_wallet_active_model.update_time = Set(chrono::Utc::now().naive_utc());

    user_wallet::Entity::update(user_wallet_active_model)
        .exec(&txn)
        .await
        .map_err(|e| async_graphql::Error::new(format!("更新用户钱包失败: {}", e)))?;

    // 8. 更新商家账户：增加冻结金额
    let updated_merchant_frozen_balance = merchant_account_model.balance_frozen + order.real_price;
    // let updated_merchant_balance = merchant_account_model.balance; // 余额暂时不变，等确认收货后再增加

    let mut merchant_account_active_model: merchant_account::ActiveModel = merchant_account_model.clone().into();
    merchant_account_active_model.balance_frozen = Set(updated_merchant_frozen_balance);
    merchant_account_active_model.update_time = Set(chrono::Utc::now().naive_utc());

    merchant_account::Entity::update(merchant_account_active_model)
        .exec(&txn)
        .await
        .map_err(|e| async_graphql::Error::new(format!("更新商家账户失败: {}", e)))?;

    let snow_id = SnowID::new(1)?;
    // 9. 创建用户钱包账单记录
    let user_wallet_bill_model = user_wallet_bill::ActiveModel {
        id: Set(snow_id.generate()),
        create_time: Set(chrono::Utc::now().naive_utc()),
        update_time: Set(chrono::Utc::now().naive_utc()),
        user_id: Set(user_id),
        user_wallet_id: Set(user_wallet_model.id),
        channel_type: Set("order_payment".to_string()),
        channel_id: Set(order_id),
        money: Set(-order.real_price), // 支出为负数
        status: Set("frozen".to_string()), // 冻结状态
    };

    user_wallet_bill::Entity::insert(user_wallet_bill_model)
        .exec(&txn)
        .await
        .map_err(|e| async_graphql::Error::new(format!("创建用户钱包账单失败: {}", e)))?;


    // 10. 创建商家账户账单记录
    let merchant_account_bill_model = merchant_account_bill::ActiveModel {
        id: Set(snow_id.generate()),
        create_time: Set(chrono::Utc::now().naive_utc()),
        update_time: Set(chrono::Utc::now().naive_utc()),
        merchant_account_id: Set(merchant_account_model.id),
        merchant_account: Set(merchant_account_model.settlement_account),
        channel_type: Set("order_income".to_string()),
        channel_id: Set(order_id),
        money: Set(order.real_price), // 收入为正数
        status: Set("frozen".to_string()), // 冻结状态
    };

    merchant_account_bill::Entity::insert(merchant_account_bill_model)
        .exec(&txn)
        .await
        .map_err(|e| async_graphql::Error::new(format!("创建商家账户账单失败: {}", e)))?;


    // 11. 更新订单状态为未配送，并设置支付信息
    let now = chrono::Utc::now().naive_utc();
    let mut order_active_model: order_main::ActiveModel = order.into();
    order_active_model.status = Set("undelivered".to_string()); // 未配送状态
    order_active_model.pay_type = Set(Some("wallet".to_string())); // 支付方式为钱包
    order_active_model.pay_time = Set(Some(now)); // 支付时间
    order_active_model.update_time = Set(now);

    let updated_order = order_main::Entity::update(order_active_model)
        .exec(&txn)
        .await
        .map_err(|e| async_graphql::Error::new(format!("更新订单失败: {}", e)))?;

    // 12. 查询订单商品信息
    let order_products = order_product_r::Entity::find()
        .filter(order_product_r::Column::OrderId.eq(updated_order.id))
        .all(&txn)
        .await
        .map_err(|e| async_graphql::Error::new(format!("查询订单商品失败: {}", e)))?
        .into_iter()
        .map(|product| OrderProductObject {
            id: product.id.to_string(),
            order_id: product.order_id.to_string(),
            product_id: product.product_id.to_string(),
            title: product.title,
            cover_addr: product.cover_addr,
            quantity: product.quantity,
            create_time: product.create_time.format("%Y-%m-%d %H:%M:%S").to_string(),
            update_time: product.update_time.format("%Y-%m-%d %H:%M:%S").to_string(),
        })
        .collect();

    // 11. 提交事务
    txn.commit().await
        .map_err(|e| async_graphql::Error::new(format!("提交事务失败: {}", e)))?;

    // 12. 构建返回对象
    let order_object = OrderObject {
        id: updated_order.id.to_string(),
        create_time: updated_order.create_time.format("%Y-%m-%d %H:%M:%S").to_string(),
        update_time: updated_order.update_time.format("%Y-%m-%d %H:%M:%S").to_string(),
        user_id: updated_order.user_id.to_string(),
        total_price: updated_order.total_price.to_string(),
        real_price: updated_order.real_price.to_string(),
        receiver_address: updated_order.receiver_address,
        receiver_name: updated_order.receiver_name,
        receiver_phone: updated_order.receiver_phone,
        pay_type: updated_order.pay_type,
        pay_time: updated_order.pay_time.map(|t| t.format("%Y-%m-%d %H:%M:%S").to_string()),
        status: updated_order.status,
        products: order_products,
    };

    Ok(order_object)
}


// 确认收货
pub async fn confirm_receipt(
    db: &DatabaseConnection,
    order_id: String,
    user_id: u64,
) -> GraphQLResult<OrderObject> {
    // 开启事务
    let txn = db.begin().await
        .map_err(|e| async_graphql::Error::new(format!("开启事务失败: {}", e)))?;

    let order_id: u64 = order_id.parse()
        .map_err(|e| async_graphql::Error::new(format!("无效的订单ID: {}", e)))?;
    // 1. 查询订单信息
    let order = order_main::Entity::find_by_id(order_id)
        .one(&txn)
        .await
        .map_err(|e| async_graphql::Error::new(format!("查询订单失败: {}", e)))?
        .ok_or_else(|| async_graphql::Error::new("订单不存在"))?;

    // 2. 验证订单是否属于当前用户
    // if order.user_id != user_id {
    //     return Err(async_graphql::Error::new("无权操作该订单"));
    // }

    // 3. 验证订单状态是否为未确认收货
    if order.status != "unconfirmed" {
        return Err(async_graphql::Error::new("订单状态不正确，无法确认收货"));
    }

    // 4. 查询订单商品信息
    let order_products = order_product_r::Entity::find()
        .filter(order_product_r::Column::OrderId.eq(order_id))
        .all(&txn)
        .await
        .map_err(|e| async_graphql::Error::new(format!("查询订单商品失败: {}", e)))?;

    // 5. 释放商品冻结库存
    for order_product in &order_products {
        // 查询商品当前信息
        let product = product_main::Entity::find_by_id(order_product.product_id)
            .one(&txn)
            .await
            .map_err(|e| async_graphql::Error::new(format!("查询商品信息失败: {}", e)))?
            .ok_or_else(|| async_graphql::Error::new(format!("商品不存在: {}", order_product.product_id)))?;

        // 释放冻结库存
        let released_frozen_stock = product.stockpile_frozen - order_product.quantity;

        // 更新商品库存
        let mut product_active_model: product_main::ActiveModel = product.into();
        product_active_model.stockpile_frozen = Set(released_frozen_stock);
        product_active_model.update_time = Set(chrono::Utc::now().naive_utc());

        product_main::Entity::update(product_active_model)
            .exec(&txn)
            .await
            .map_err(|e| async_graphql::Error::new(format!("释放商品冻结库存失败: {}", e)))?;
    }


    // 4. 查询用户钱包信息
    let user_wallet_model = user_wallet::Entity::find()
        .filter(user_wallet::Column::UserId.eq(user_id))
        .one(&txn)
        .await
        .map_err(|e| async_graphql::Error::new(format!("查询用户钱包失败: {}", e)))?
        .ok_or_else(|| async_graphql::Error::new("用户钱包不存在"))?;

    // 5. 查询商家账户信息（根据结算账户号）
    let merchant_account_model = merchant_account::Entity::find()
        .filter(merchant_account::Column::SettlementAccount.eq("6222600810123456789"))
        .one(&txn)
        .await
        .map_err(|e| async_graphql::Error::new(format!("查询商家账户失败: {}", e)))?
        .ok_or_else(|| async_graphql::Error::new("商家账户不存在"))?;

    // 6. 更新用户钱包：扣除冻结金额
    let updated_user_frozen_balance = user_wallet_model.frozen_balance - order.real_price;

    let mut user_wallet_active_model: user_wallet::ActiveModel = user_wallet_model.clone().into();
    user_wallet_active_model.frozen_balance = Set(updated_user_frozen_balance);
    user_wallet_active_model.update_time = Set(chrono::Utc::now().naive_utc());

    user_wallet::Entity::update(user_wallet_active_model)
        .exec(&txn)
        .await
        .map_err(|e| async_graphql::Error::new(format!("更新用户钱包失败: {}", e)))?;

    // 7. 更新商家账户：增加余额并减少冻结金额
    let updated_merchant_balance = merchant_account_model.balance + order.real_price;
    let updated_merchant_frozen_balance = merchant_account_model.balance_frozen - order.real_price;

    let mut merchant_account_active_model: merchant_account::ActiveModel = merchant_account_model.clone().into();
    merchant_account_active_model.balance = Set(updated_merchant_balance);
    merchant_account_active_model.balance_frozen = Set(updated_merchant_frozen_balance);
    merchant_account_active_model.update_time = Set(chrono::Utc::now().naive_utc());

    merchant_account::Entity::update(merchant_account_active_model)
        .exec(&txn)
        .await
        .map_err(|e| async_graphql::Error::new(format!("更新商家账户失败: {}", e)))?;

    // 8. 更新用户钱包账单状态为已完成
    user_wallet_bill::Entity::update_many()
        .filter(user_wallet_bill::Column::UserId.eq(user_id))
        .filter(user_wallet_bill::Column::ChannelId.eq(order_id))
        .filter(user_wallet_bill::Column::ChannelType.eq("order_payment"))
        .set(user_wallet_bill::ActiveModel {
            status: Set("completed".to_string()),
            update_time: Set(chrono::Utc::now().naive_utc()),
            ..Default::default()
        })
        .exec(&txn)
        .await
        .map_err(|e| async_graphql::Error::new(format!("更新用户钱包账单失败: {}", e)))?;

    // 9. 更新商家账户账单状态为已完成
    merchant_account_bill::Entity::update_many()
        .filter(merchant_account_bill::Column::MerchantAccount.eq(merchant_account_model.settlement_account))
        .filter(merchant_account_bill::Column::ChannelId.eq(order_id))
        .filter(merchant_account_bill::Column::ChannelType.eq("order_income"))
        .set(merchant_account_bill::ActiveModel {
            status: Set("completed".to_string()),
            update_time: Set(chrono::Utc::now().naive_utc()),
            ..Default::default()
        })
        .exec(&txn)
        .await
        .map_err(|e| async_graphql::Error::new(format!("更新商家账户账单失败: {}", e)))?;

    // 10. 更新订单状态为已完成
    let now = chrono::Utc::now().naive_utc();
    let mut order_active_model: order_main::ActiveModel = order.into();
    order_active_model.status = Set("completed".to_string()); // 已完成状态
    order_active_model.update_time = Set(now);

    let updated_order = order_main::Entity::update(order_active_model)
        .exec(&txn)
        .await
        .map_err(|e| async_graphql::Error::new(format!("更新订单失败: {}", e)))?;

    // 11. 查询订单商品信息
    let order_products = order_product_r::Entity::find()
        .filter(order_product_r::Column::OrderId.eq(updated_order.id))
        .all(&txn)
        .await
        .map_err(|e| async_graphql::Error::new(format!("查询订单商品失败: {}", e)))?
        .into_iter()
        .map(|product| OrderProductObject {
            id: product.id.to_string(),
            order_id: product.order_id.to_string(),
            product_id: product.product_id.to_string(),
            title: product.title,
            cover_addr: product.cover_addr,
            quantity: product.quantity,
            create_time: product.create_time.format("%Y-%m-%d %H:%M:%S").to_string(),
            update_time: product.update_time.format("%Y-%m-%d %H:%M:%S").to_string(),
        })
        .collect();

    // 12. 提交事务
    txn.commit().await
        .map_err(|e| async_graphql::Error::new(format!("提交事务失败: {}", e)))?;

    // 13. 构建返回对象
    let order_object = OrderObject {
        id: updated_order.id.to_string(),
        create_time: updated_order.create_time.format("%Y-%m-%d %H:%M:%S").to_string(),
        update_time: updated_order.update_time.format("%Y-%m-%d %H:%M:%S").to_string(),
        user_id: updated_order.user_id.to_string(),
        total_price: updated_order.total_price.to_string(),
        real_price: updated_order.real_price.to_string(),
        receiver_address: updated_order.receiver_address,
        receiver_name: updated_order.receiver_name,
        receiver_phone: updated_order.receiver_phone,
        pay_type: updated_order.pay_type,
        pay_time: updated_order.pay_time.map(|t| t.format("%Y-%m-%d %H:%M:%S").to_string()),
        status: updated_order.status,
        products: order_products,
    };

    Ok(order_object)
}

// 已送达接口
pub async fn mark_as_delivered(
    db: &DatabaseConnection,
    order_id: String,
    user_id: u64,
) -> GraphQLResult<OrderObject> {
    
    let order_id : u64 = order_id.parse()
        .map_err(|e| async_graphql::Error::new(format!("无效的订单ID: {}", e)))?;
    // 1. 查询订单信息
    let order = order_main::Entity::find_by_id(order_id)
        .one(db)
        .await
        .map_err(|e| async_graphql::Error::new(format!("查询订单失败: {}", e)))?
        .ok_or_else(|| async_graphql::Error::new("订单不存在"))?;

    // 2. 验证订单是否属于当前用户（如果是用户操作）或验证权限（如果是管理员操作）
    // 这里假设只有管理员或配送员可以调用此接口，因此不验证用户ID
    // 如果需要验证用户权限，请取消下面的注释
    // if order.user_id != user_id {
    //     return Err(async_graphql::Error::new("无权操作该订单"));
    // }

    // 3. 验证订单状态是否为未配送
    if order.status != "undelivered" {
        return Err(async_graphql::Error::new("订单状态不正确，无法标记为已送达"));
    }

    // 4. 更新订单状态为未确认收货
    let now = chrono::Utc::now().naive_utc();
    let mut order_active_model: order_main::ActiveModel = order.into();
    order_active_model.status = Set("unconfirmed".to_string()); // 未确认收货状态
    order_active_model.update_time = Set(now);

    let updated_order = order_main::Entity::update(order_active_model)
        .exec(db)
        .await
        .map_err(|e| async_graphql::Error::new(format!("更新订单失败: {}", e)))?;

    // 5. 查询订单商品信息
    let order_products = order_product_r::Entity::find()
        .filter(order_product_r::Column::OrderId.eq(updated_order.id))
        .all(db)
        .await
        .map_err(|e| async_graphql::Error::new(format!("查询订单商品失败: {}", e)))?
        .into_iter()
        .map(|product| OrderProductObject {
            id: product.id.to_string(),
            order_id: product.order_id.to_string(),
            product_id: product.product_id.to_string(),
            title: product.title,
            cover_addr: product.cover_addr,
            quantity: product.quantity,
            create_time: product.create_time.format("%Y-%m-%d %H:%M:%S").to_string(),
            update_time: product.update_time.format("%Y-%m-%d %H:%M:%S").to_string(),
        })
        .collect();

    // 6. 构建返回对象
    let order_object = OrderObject {
        id: updated_order.id.to_string(),
        create_time: updated_order.create_time.format("%Y-%m-%d %H:%M:%S").to_string(),
        update_time: updated_order.update_time.format("%Y-%m-%d %H:%M:%S").to_string(),
        user_id: updated_order.user_id.to_string(),
        total_price: updated_order.total_price.to_string(),
        real_price: updated_order.real_price.to_string(),
        receiver_address: updated_order.receiver_address,
        receiver_name: updated_order.receiver_name,
        receiver_phone: updated_order.receiver_phone,
        pay_type: updated_order.pay_type,
        pay_time: updated_order.pay_time.map(|t| t.format("%Y-%m-%d %H:%M:%S").to_string()),
        status: updated_order.status,
        products: order_products,
    };

    Ok(order_object)
}



// 取消订单接口
pub async fn cancel_order(
    db: &DatabaseConnection,
    order_id: String,
    user_id: u64,
) -> GraphQLResult<OrderObject> {
    // 开启事务
    let txn = db.begin().await
        .map_err(|e| async_graphql::Error::new(format!("开启事务失败: {}", e)))?;

    let order_id: u64 = order_id.parse()
        .map_err(|e| async_graphql::Error::new(format!("无效的订单ID: {}", e)))?;
    
    // 1. 查询订单信息
    let order = order_main::Entity::find_by_id(order_id)
        .one(&txn)
        .await
        .map_err(|e| async_graphql::Error::new(format!("查询订单失败: {}", e)))?
        .ok_or_else(|| async_graphql::Error::new("订单不存在"))?;

    // // 2. 验证订单是否属于当前用户
    // if order.user_id != user_id {
    //     return Err(async_graphql::Error::new("无权操作该订单"));
    // }

    // 3. 验证订单状态是否可以取消
    match order.status.as_str() {
        "non_pay" | "undelivered" | "unconfirmed" => {
            // 这些状态可以取消
        }
        _ => {
            return Err(async_graphql::Error::new("订单状态不正确，无法取消"));
        }
    }

    // 4. 如果是未支付状态，直接修改订单状态即可
    if order.status == "non_pay" {
        // 查询订单商品信息
        let order_products = order_product_r::Entity::find()
            .filter(order_product_r::Column::OrderId.eq(order_id))
            .all(&txn)
            .await
            .map_err(|e| async_graphql::Error::new(format!("查询订单商品失败: {}", e)))?;

        // 还原商品库存
        for order_product in &order_products {
            // 查询商品当前信息
            let product = product_main::Entity::find_by_id(order_product.product_id)
                .one(&txn)
                .await
                .map_err(|e| async_graphql::Error::new(format!("查询商品信息失败: {}", e)))?
                .ok_or_else(|| async_graphql::Error::new(format!("商品不存在: {}", order_product.product_id)))?;

            // 还原冻结库存
            let restored_frozen_stock = product.stockpile_frozen - order_product.quantity;
            let restored_available_stock = product.stockpile + order_product.quantity;

            // 更新商品库存
            let mut product_active_model: product_main::ActiveModel = product.into();
            product_active_model.stockpile_frozen = Set(restored_frozen_stock);
            product_active_model.stockpile = Set(restored_available_stock);
            product_active_model.update_time = Set(chrono::Utc::now().naive_utc());

            product_main::Entity::update(product_active_model)
                .exec(&txn)
                .await
                .map_err(|e| async_graphql::Error::new(format!("还原商品库存失败: {}", e)))?;
        }

        // 更新订单状态
        let now = chrono::Utc::now().naive_utc();
        let mut order_active_model: order_main::ActiveModel = order.into();
        order_active_model.status = Set("canceled".to_string()); // 取消状态
        order_active_model.update_time = Set(now);

        let updated_order = order_main::Entity::update(order_active_model)
            .exec(&txn)
            .await
            .map_err(|e| async_graphql::Error::new(format!("更新订单失败: {}", e)))?;

        // 查询订单商品信息用于返回
        let order_products_result = order_product_r::Entity::find()
            .filter(order_product_r::Column::OrderId.eq(updated_order.id))
            .all(&txn)
            .await
            .map_err(|e| async_graphql::Error::new(format!("查询订单商品失败: {}", e)))?
            .into_iter()
            .map(|product| OrderProductObject {
                id: product.id.to_string(),
                order_id: product.order_id.to_string(),
                product_id: product.product_id.to_string(),
                title: product.title,
                cover_addr: product.cover_addr,
                quantity: product.quantity,
                create_time: product.create_time.format("%Y-%m-%d %H:%M:%S").to_string(),
                update_time: product.update_time.format("%Y-%m-%d %H:%M:%S").to_string(),
            })
            .collect();

        // 提交事务
        txn.commit().await
            .map_err(|e| async_graphql::Error::new(format!("提交事务失败: {}", e)))?;

        // 构建返回对象
        let order_object = OrderObject {
            id: updated_order.id.to_string(),
            create_time: updated_order.create_time.format("%Y-%m-%d %H:%M:%S").to_string(),
            update_time: updated_order.update_time.format("%Y-%m-%d %H:%M:%S").to_string(),
            user_id: updated_order.user_id.to_string(),
            total_price: updated_order.total_price.to_string(),
            real_price: updated_order.real_price.to_string(),
            receiver_address: updated_order.receiver_address,
            receiver_name: updated_order.receiver_name,
            receiver_phone: updated_order.receiver_phone,
            pay_type: updated_order.pay_type,
            pay_time: updated_order.pay_time.map(|t| t.format("%Y-%m-%d %H:%M:%S").to_string()),
            status: updated_order.status,
            products: order_products_result,
        };

        return Ok(order_object);
    }

    // 5. 如果是已支付但未确认收货的状态 (undelivered 或 unconfirmed)

    // 查询订单商品信息
    let order_products = order_product_r::Entity::find()
        .filter(order_product_r::Column::OrderId.eq(order_id))
        .all(&txn)
        .await
        .map_err(|e| async_graphql::Error::new(format!("查询订单商品失败: {}", e)))?;

    // 还原商品库存
    for order_product in &order_products {
        // 查询商品当前信息
        let product = product_main::Entity::find_by_id(order_product.product_id)
            .one(&txn)
            .await
            .map_err(|e| async_graphql::Error::new(format!("查询商品信息失败: {}", e)))?
            .ok_or_else(|| async_graphql::Error::new(format!("商品不存在: {}", order_product.product_id)))?;

        // 还原冻结库存
        let restored_frozen_stock = product.stockpile_frozen - order_product.quantity;
        let restored_available_stock = product.stockpile + order_product.quantity;

        // 更新商品库存
        let mut product_active_model: product_main::ActiveModel = product.into();
        product_active_model.stockpile_frozen = Set(restored_frozen_stock);
        product_active_model.stockpile = Set(restored_available_stock);
        product_active_model.update_time = Set(chrono::Utc::now().naive_utc());

        product_main::Entity::update(product_active_model)
            .exec(&txn)
            .await
            .map_err(|e| async_graphql::Error::new(format!("还原商品库存失败: {}", e)))?;
    }

    // 查询用户钱包信息
    let user_wallet_model = user_wallet::Entity::find()
        .filter(user_wallet::Column::UserId.eq(user_id))
        .one(&txn)
        .await
        .map_err(|e| async_graphql::Error::new(format!("查询用户钱包失败: {}", e)))?
        .ok_or_else(|| async_graphql::Error::new("用户钱包不存在"))?;

    // 查询商家账户信息（根据结算账户号）
    let merchant_account_model = merchant_account::Entity::find()
        .filter(merchant_account::Column::SettlementAccount.eq(6222600810123456789u64))
        .one(&txn)
        .await
        .map_err(|e| async_graphql::Error::new(format!("查询商家账户失败: {}", e)))?
        .ok_or_else(|| async_graphql::Error::new("商家账户不存在"))?;

    // 6. 更新用户钱包：增加余额并减少冻结金额
    let updated_user_balance = user_wallet_model.balance + order.real_price;
    let updated_user_frozen_balance = user_wallet_model.frozen_balance - order.real_price;

    let mut user_wallet_active_model: user_wallet::ActiveModel = user_wallet_model.clone().into();
    user_wallet_active_model.balance = Set(updated_user_balance);
    user_wallet_active_model.frozen_balance = Set(updated_user_frozen_balance);
    user_wallet_active_model.update_time = Set(chrono::Utc::now().naive_utc());

    user_wallet::Entity::update(user_wallet_active_model)
        .exec(&txn)
        .await
        .map_err(|e| async_graphql::Error::new(format!("更新用户钱包失败: {}", e)))?;

    // 7. 更新商家账户：减少冻结金额
    let updated_merchant_frozen_balance = merchant_account_model.balance_frozen - order.real_price;

    let mut merchant_account_active_model: merchant_account::ActiveModel = merchant_account_model.clone().into();
    merchant_account_active_model.balance_frozen = Set(updated_merchant_frozen_balance);
    merchant_account_active_model.update_time = Set(chrono::Utc::now().naive_utc());

    merchant_account::Entity::update(merchant_account_active_model)
        .exec(&txn)
        .await
        .map_err(|e| async_graphql::Error::new(format!("更新商家账户失败: {}", e)))?;

    // 8. 更新用户钱包账单状态为已取消
    user_wallet_bill::Entity::update_many()
        .filter(user_wallet_bill::Column::UserId.eq(user_id))
        .filter(user_wallet_bill::Column::ChannelId.eq(order_id))
        .filter(user_wallet_bill::Column::ChannelType.eq("order_payment"))
        .set(user_wallet_bill::ActiveModel {
            status: Set("canceled".to_string()),
            update_time: Set(chrono::Utc::now().naive_utc()),
            ..Default::default()
        })
        .exec(&txn)
        .await
        .map_err(|e| async_graphql::Error::new(format!("更新用户钱包账单失败: {}", e)))?;

    let snow_id = SnowID::new(1)?;
    // 9. 创建新的用户钱包账单记录（退款）
    let user_wallet_refund_bill_model = user_wallet_bill::ActiveModel {
        id: Set(snow_id.generate()),
        create_time: Set(chrono::Utc::now().naive_utc()),
        update_time: Set(chrono::Utc::now().naive_utc()),
        user_id: Set(user_id),
        user_wallet_id: Set(user_wallet_model.id),
        channel_type: Set("order_refund".to_string()),
        channel_id: Set(order_id),
        money: Set(order.real_price), // 退款为正数
        status: Set("completed".to_string()), // 退款立即完成
    };

    user_wallet_bill::Entity::insert(user_wallet_refund_bill_model)
        .exec(&txn)
        .await
        .map_err(|e| async_graphql::Error::new(format!("创建用户退款账单失败: {}", e)))?;

    // 10. 更新商家账户账单状态为已取消
    merchant_account_bill::Entity::update_many()
        .filter(merchant_account_bill::Column::MerchantAccount.eq(merchant_account_model.settlement_account))
        .filter(merchant_account_bill::Column::ChannelId.eq(order_id))
        .filter(merchant_account_bill::Column::ChannelType.eq("order_income"))
        .set(merchant_account_bill::ActiveModel {
            status: Set("canceled".to_string()),
            update_time: Set(chrono::Utc::now().naive_utc()),
            ..Default::default()
        })
        .exec(&txn)
        .await
        .map_err(|e| async_graphql::Error::new(format!("更新商家账户账单失败: {}", e)))?;

    // 11. 创建新的商家账户账单记录（退款）
    let merchant_account_refund_bill_model = merchant_account_bill::ActiveModel {
        id: Set(snow_id.generate()),
        create_time: Set(chrono::Utc::now().naive_utc()),
        update_time: Set(chrono::Utc::now().naive_utc()),
        merchant_account_id: Set(merchant_account_model.id),
        merchant_account: Set(merchant_account_model.settlement_account),
        channel_type: Set("order_refund".to_string()),
        channel_id: Set(order_id),
        money: Set(-order.real_price), // 退款为负数
        status: Set("completed".to_string()), // 退款立即完成
    };

    merchant_account_bill::Entity::insert(merchant_account_refund_bill_model)
        .exec(&txn)
        .await
        .map_err(|e| async_graphql::Error::new(format!("创建商家退款账单失败: {}", e)))?;

    // 12. 更新订单状态为已取消
    let now = chrono::Utc::now().naive_utc();
    let mut order_active_model: order_main::ActiveModel = order.into();
    order_active_model.status = Set("canceled".to_string()); // 取消状态
    order_active_model.update_time = Set(now);

    let updated_order = order_main::Entity::update(order_active_model)
        .exec(&txn)
        .await
        .map_err(|e| async_graphql::Error::new(format!("更新订单失败: {}", e)))?;

    // 13. 查询订单商品信息
    let order_products = order_product_r::Entity::find()
        .filter(order_product_r::Column::OrderId.eq(updated_order.id))
        .all(&txn)
        .await
        .map_err(|e| async_graphql::Error::new(format!("查询订单商品失败: {}", e)))?
        .into_iter()
        .map(|product| OrderProductObject {
            id: product.id.to_string(),
            order_id: product.order_id.to_string(),
            product_id: product.product_id.to_string(),
            title: product.title,
            cover_addr: product.cover_addr,
            quantity: product.quantity,
            create_time: product.create_time.format("%Y-%m-%d %H:%M:%S").to_string(),
            update_time: product.update_time.format("%Y-%m-%d %H:%M:%S").to_string(),
        })
        .collect();

    // 14. 提交事务
    txn.commit().await
        .map_err(|e| async_graphql::Error::new(format!("提交事务失败: {}", e)))?;

    // 15. 构建返回对象
    let order_object = OrderObject {
        id: updated_order.id.to_string(),
        create_time: updated_order.create_time.format("%Y-%m-%d %H:%M:%S").to_string(),
        update_time: updated_order.update_time.format("%Y-%m-%d %H:%M:%S").to_string(),
        user_id: updated_order.user_id.to_string(),
        total_price: updated_order.total_price.to_string(),
        real_price: updated_order.real_price.to_string(),
        receiver_address: updated_order.receiver_address,
        receiver_name: updated_order.receiver_name,
        receiver_phone: updated_order.receiver_phone,
        pay_type: updated_order.pay_type,
        pay_time: updated_order.pay_time.map(|t| t.format("%Y-%m-%d %H:%M:%S").to_string()),
        status: updated_order.status,
        products: order_products,
    };

    Ok(order_object)
}